/**
 * 
 */
package org.kernely.web.context;

import java.io.IOException;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.framework.Bundle;
import org.osgi.service.http.HttpContext;

/**
 * Kernely http context
 * This context should be unique in all kernely in order to be able to apply filter everywhere.
 * @author g.breton
 * 
 */
public class KernelyHttpContext implements HttpContext {

	//the caller bundle
	private Bundle bundle;

	/**
	 * Creates the kernely http context with the bundle
	 * @param bundle
	 */
	public KernelyHttpContext(Bundle bundle) {
		this.bundle = bundle;
	}

	/**
	 * @see org.osgi.service.http.HttpContext#handleSecurity(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public final boolean handleSecurity(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//security is handled by shiro
		//TODO study a poosibility to put shiro here
		return true;
	}

	/**
	 * @see org.osgi.service.http.HttpContext#getResource(java.lang.String)
	 */
	@Override
	public final URL getResource(String name) {
		URL resource = null;
		// TODO FIX IT
		if(name.startsWith("/VAADIN/")){
			Bundle[] bundles = bundle.getBundleContext().getBundles();
			// Retrieve Vaadin bundle
			for(Bundle b : bundles){
				if(b.getSymbolicName().equals("com.vaadin")){
					resource = b.getResource(name);
				}
			}
		}
		else{
			resource = bundle.getResource(name);
		}
		return resource;
	}

	/**
	 * @see org.osgi.service.http.HttpContext#getMimeType(java.lang.String)
	 */
	@Override
	public final String getMimeType(String pName) {
		if(pName.endsWith("js")){
			return "text/javascript";
		}
		else if(pName.endsWith("css")){
			return "text/css";
		}
		else if(pName.endsWith("html") || pName.endsWith("vm")){
			return "text/html";
		}
		else if(pName.endsWith("png")){
			return "image/png";
		}
		else if(pName.endsWith("gif")){
			return "image/gif";
		}
		else{
			return null;
		}
	}

}
